﻿using Furion;
using Furion.Authorization;
using Furion.DataEncryption;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Threading.Tasks;

namespace FurionJWTDemo.Web.Entry.Controller
{
    public class AuthController : ControllerBase
    {
        [AllowAnonymous]
        [Route("api/auth")]
        [HttpGet]
        public string Auth(string userName, string pwd)
        {
            string output = string.Empty;

            if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(pwd))
            {
                // 生成 token
                var jwtSettings = App.GetOptions<JWTSettingsOptions>();
                var datetimeOffset = new DateTimeOffset(DateTime.Now);
                if (jwtSettings.ExpiredTime != null)
                    output = JWTEncryption.Encrypt(jwtSettings.IssuerSigningKey,
                        new Dictionary<string, object>()
                        {
                        {"UserId", userName}, // 存储Id
                        //{"IsAdmin", true}, // 管理员登录
                        {JwtRegisteredClaimNames.Iat, datetimeOffset.ToUnixTimeSeconds()},
                        {JwtRegisteredClaimNames.Nbf, datetimeOffset.ToUnixTimeSeconds()},
                        {
                            JwtRegisteredClaimNames.Exp,
                            new DateTimeOffset(
                                    DateTime.Now.AddSeconds(
                                        jwtSettings.ExpiredTime.Value * 60 * 60 * 24 * 30))
                                .ToUnixTimeSeconds()
                        },
                        {JwtRegisteredClaimNames.Iss, jwtSettings.ValidIssuer},
                        {JwtRegisteredClaimNames.Aud, jwtSettings.ValidAudience}
                        });

                //// 设置 Swagger 刷新自动授权
                //if (_httpContextAccessor.HttpContext != null)
                //    _httpContextAccessor.HttpContext.Response.Headers["access-token"] = output.AccessToken;
            }

            return output;
        }
    }
}
